package com.alameda.common.aop;

import com.alameda.common.commonpent.lock.api.DistributedLockTemplate;
import com.alameda.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 分布式锁aop
 *
 * @author Lv
 * @date 2024/8/2
 */
@Slf4j
@Order(1)
@Aspect
@Component
public class ZkLockAop {

    /**
     * 定义切入点
     */
    @Pointcut("@annotation(com.alameda.common.annotation.Lock)")
    public void point() {
    }

    @Autowired
    private DistributedLockTemplate distributedLockTemplate;

    /**
     * 环绕处理
     *
     * @param proceedingJoinPoint 切点对象
     */
    @Around("point()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) {
        distributedLockTemplate.acquireLock();
        Object proceed = null;
        try {
            proceed = proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            log.error("执行错误", throwable);
            BusinessException.throwException(throwable);
        } finally {
            distributedLockTemplate.releaseLock();
        }
        return proceed;
    }
}
